//
//  MeDetailViewController.m
//  Dear
//
//  Created by n22 on 15/7/15.
//  Copyright (c) 2015年 陈俊俊. All rights reserved.
//

#import "MeDetailViewController.h"
#import "DetailCell.h"
#import "DetailCellFirst.h"
#import "UpdNickerViewController.h"
#import "UpdPassViewController.h"
#import "HeadViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
#import "TabBarController.h"
#import "UploadRequest.h"
#import "TPFileManager.h"
@interface MeDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UITableView * _tableView;
    UIImageView *_headImageView;
    UIImagePickerController *_imagePicker;
    UIImage *_headImage;
}
@end

@implementation MeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTitleViewWith:@"详细信息"];
    self.view.backgroundColor = RGBA(246, 246, 246, 1);
    [self uiConfig];
    
}
- (void)uiConfig {
    _tableView = [[UITableView alloc]initWithFrame:(CGRectMake(0, 0,ScreenSize.width , ScreenSize.height - 64)) style:(UITableViewStylePlain)];
    _tableView.backgroundColor = RGBA(246, 246, 246, 1);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 50)];
    UIButton *footBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    footBtn.frame = CGRectMake(0, 10, ScreenSize.width, 40);
    footBtn.backgroundColor = [UIColor whiteColor];
    [footBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [footBtn setTitleColor:RGBA(207, 49, 37, 1) forState:UIControlStateNormal];
    [footBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:footBtn];
    [self.view addSubview:footView];
    _tableView.tableFooterView = footView;
    [self.view addSubview:_tableView];
    
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    }
    
}
#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    }else {
        
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        DetailCellFirst * cell = [[[NSBundle mainBundle]loadNibNamed:@"DetailCellFirst" owner:self options:nil]lastObject];
        NSString *filePhoto = @"";
        if (![TPFileManager getPhotoStr:[NSString stringWithFormat:@"%@%@",HeadImage,[DearUser sharedInstance].userId]]) {
            NSArray *images = [[DearUser sharedInstance].picture componentsSeparatedByString:@","];
            if (images.count == 0) {
                filePhoto = @"shoot";
            }else{
                filePhoto = images[0];
            }
        }else{
            filePhoto = HeadImage;
        }
        NSArray * arr = @[[DearUser sharedInstance].txtName,filePhoto];
        [cell showDataWithArray:arr];
        _headImageView = cell.headImageView;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        return cell;
        
    }else {
        NSArray * declareArr =@[ @[@"",@"昵称",@"账号",@"修改密码"],@[@"关联账号信息"]];
        NSArray * details =@[ @[@"",[DearUser sharedInstance].txtName,[DearUser sharedInstance].userName,@""],@[@""]];
        static NSString * cellID = @"DetailCell";
        DetailCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"DetailCell" owner:self options:nil]lastObject];
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row == 2 && indexPath.section == 0) {
            cell.moreImageView.hidden = YES;
        }else{
            cell.moreImageView.hidden = NO;
        }
        [cell showDataWithTitle:declareArr[indexPath.section][indexPath.row] detailContent:details[indexPath.section][indexPath.row]];
        return cell;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section== 0) {
        return 0;
    }else {
        return 44;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        
        UILabel * label = [[UILabel alloc]initWithFrame:(CGRectMake(10, 0, 100, 44))];
        label.text = @"   关联账号";
        label.textAlignment= NSTextAlignmentLeft;
        label.textColor = [UIColor grayColor];
        return label;
    }else {
        return nil;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 60;
    }else {
        return 42;
    }
    
}
#pragma mark -点击cell触发事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if(indexPath.row == 0){
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册选择",@"拍照", nil];
            [sheet showInView:self.view];
        }else if (indexPath.row == 1) {
            UpdNickerViewController *uvc = [[UpdNickerViewController alloc]init];
            [self.navigationController pushViewController:uvc animated:YES];
        }else  if (indexPath.row == 3) {
            UpdPassViewController *uvc = [[UpdPassViewController alloc]init];
            [self.navigationController pushViewController:uvc animated:YES];
        }
    }else {
        if ([[DearUser sharedInstance].linkFlag integerValue] == 1) {
            HeadViewController *hvc = [[HeadViewController alloc]init];
            [self.navigationController pushViewController:hvc animated:YES];
        }else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"没有关联信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}
#pragma mark  - 退出登录操作
- (void)btnClick{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"确定要退出吗" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
#pragma mark - alertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [DearUser resetDear];
    //关闭定时器
    if ([[UploadRequest sharedInstance].timer isValid]) {
        [[UploadRequest sharedInstance].timer invalidate];
    }
    //清空上传信息
    [UploadRequest resetUpload];
    //切换界面
    LoginViewController * lvc = [[LoginViewController alloc]init];
    UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:lvc];
    [DearAppDelegate window].rootViewController = navC;
    

}

#pragma mark - sheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//设置来源
            _imagePicker.allowsEditing=YES;//允许编辑
            [self presentViewController:_imagePicker animated:NO completion:nil];
        }
    }else if(buttonIndex == 1){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            _imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            _imagePicker.cameraDevice=UIImagePickerControllerCameraDeviceRear;//选择摄像头
            _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;//摄像头模式
            [self presentViewController:_imagePicker animated:NO completion:nil];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该设备没有照相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
        }
    }
}

#pragma mark- UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
       NSLog(@"info:%@",info);
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    NSLog(@"mediaType:%@",mediaType);
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (_imagePicker.allowsEditing) {
            image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
        }else{
            image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
        }
        [picker dismissViewControllerAnimated:YES completion:^{
            NSData *data = UIImageJPEGRepresentation(image, 0.2);
            _headImage = image;
            [self uploadImage:data];
        }];
    }
}
- (void)uploadImage:(NSData *)imageData{
    
    NSDictionary *dict = @{@"userId":[DearUser sharedInstance].userId,@"picture":imageData,@"imagePath":@"tt.jpg"};
    NSString *url = [ServerUrl stringByAppendingFormat:@"/%@",DearHttpModifyHead];
    [[HttpRequest sharedInstance] POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [DearLoadingView hideHUD];
        if (responseObject) {
            NSDictionary *dict = (NSDictionary *)responseObject;
            if ([dict[@"Result"] integerValue] == 0)
            {
                //保存文件中
                [TPFileManager savePhotoFor:imageData nameStr:[NSString stringWithFormat:@"%@%@",HeadImage,[DearUser sharedInstance].userId]];
                [_headImageView setImage:_headImage];//显示照片
                self.getImageView();
            }else {
                [DearLoadingView showTips:dict[@"Message"]];
            }
        }else{
            [DearLoadingView showTips:@"获取失败"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [DearLoadingView hideHUD];
        [DearLoadingView showTips:error];
    }];

}

//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_tableView) {
        [_tableView reloadData];
    }
}


@end
